package cn.liutao.common.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liutao
 * @Description 用于处理跨域的过滤器
 * @date 2023/10/30 22:56
 * @Version 1.0
 */
public class CORSFilter extends HttpFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //允许跨域的源
        response.setHeader("Access-Control-Allow-Origin", "*");
        //跨域支持的方法
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
        //表示服务器允许请求的字段，可以写多个
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization");
        response.setHeader("Access-Control-Max-Age", "false");  //是否允携带凭证（cookie），True 和 上面的 * 不能共存
        response.setHeader("Access-Control-Allow-Credentials", "10");  //下次预检的缓存时间
        filterChain.doFilter(servletRequest,response);
    }
}
